package cn.tedu.crm.base.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.tedu.crm.base.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class CaptchaService {

    private static final String CAPTCHA_CACHE_KEY = "captcha:";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 生成验证码
     *
     * @return 验证码key+base64
     */
    public Map<String, Object> generateCaptcha() {
        // 生成验证码
        GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(100, 40, 4);
        // 缓存验证码
        String captchaKey = UUID.randomUUID().toString();
        String captchaCacheKey = CAPTCHA_CACHE_KEY + captchaKey;
        redisTemplate.opsForValue().set(captchaCacheKey, gifCaptcha.getCode(), 2, TimeUnit.MINUTES);
        // 返回验证码
        Map<String, Object> result = new HashMap<>();
        result.put("captchaKey", captchaKey);
        result.put("captchaBase64", gifCaptcha.getImageBase64Data());
        return result;
    }

    /**
     * 验证验证码
     *
     * @param captchaKey 验证码key
     * @param captcha    验证码
     */
    public void verifyCaptcha(String captchaKey, String captcha) {
        String captchaCacheKey = CAPTCHA_CACHE_KEY + captchaKey;
        Object value = redisTemplate.opsForValue().get(captchaCacheKey);
        redisTemplate.delete(captchaCacheKey);
        if (Objects.isNull(value)) {
            throw new ServiceException("验证码已过期");
        }
        if (!value.toString().equalsIgnoreCase(captcha)) {
            throw new ServiceException("验证码不正确");
        }
    }

}
